package com.cloudlead.common.lang.persistence;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2015/10/15.
 */
public class ObjectList implements java.io.Serializable{
    public List data;
    public ObjectList(List object, String columns){
        {
            data= new ArrayList();
            for (Object o:object){
                HashMap map = new HashMap();
                for (String fld:columns.split(",")) {
                    fld = fld.trim();
                    while (fld.indexOf("  ")>=0) fld=fld.replaceAll("  "," ");
                    String fName=fld;
                    if (fld.indexOf(" ")>0){
                        fName = fld.substring(fld.indexOf(" ")+1);
                        fld = fld.substring(0,fld.indexOf(" "));
                    }
                    if (fld.indexOf(".")>0){
                        String[] exFld= fld.split("\\.");
                        Object childObj=getFieldValue(o,exFld[0]);
                        map.put(fName,getFieldValue(childObj,exFld[1]));
                    }else{
                        map.put(fName,getFieldValue(o,fld));
                    }
                }
                data.add(map);
            }
        }
    }
    public Object getFieldValue(Object obj, String fldName){
        if (obj==null) return null;
        try {
            Field[] fields = obj.getClass().getDeclaredFields();
            for(Field f : fields) {
                f.setAccessible(true);
                if (f.getName().equalsIgnoreCase(fldName))
                    return f.get(obj);
            }
        } catch (IllegalAccessException e) {
            return null;
        }
        return null;
    }
}
